import type { RouteLocationNormalized, Router } from 'vue-router';
import { setRouteEmitter } from '@/utils/route-listener';
import setupUserLoginInfoGuard from './userLoginInfo';
import setupPermissionGuard from './permission';
import { useAppStore, useUserStore } from "@/store";

function setupPageGuard(router: Router) {
  router.beforeEach(async (to) => {
    // emit route change
    setRouteEmitter(to);
    setPageRole(to)
  });
}

function setPageRole(to: RouteLocationNormalized){
  const userStore = useUserStore();
  const appStore = useAppStore()
  // const res = await userStore.switchRoles()
  // 如果路由配置的meta中role != user 就把store.role = admin
  if (to.meta.roles && to.meta.roles[0] !== "user") {
    userStore.role = "admin"
  } else [
    userStore.role = 'user'
  ]
  // to.meta.roles && (userStore.role = to.meta.roles[0] !== "user" || "admin")
  // if (['/doctor/doctorHome', '/doctor/doctorDetail'].includes(path)) {
  //   userStore.role = 'user'//标注医生
  // } else {
  //   userStore.role = 'admin'//管理员
  // }
  appStore.updateSettings({
    hideMenu: userStore.role === "user",
  });
}

export default function createRouteGuard(router: Router) {
  setupPageGuard(router);
  setupUserLoginInfoGuard(router);
  setupPermissionGuard(router);
}
